﻿using System.Collections.Generic;
using CodeParser.Tokens;

namespace CodeParser.Expressions
{
    public class FunctionDefinitionParser
        : ExpressionParser
    {

        public FunctionDefinitionParser()
        {
            ArgumentListParsers = new List<ExpressionParser>();
            CodeBlockParsers = new List<ExpressionParser>();
        }

        public override Expression Parse(Token[] tokens, int index)
        {
            if (index < tokens.Length - 5 && tokens[index].Type == TokenType.Identifier && tokens[index + 1].Type == TokenType.Identifier && tokens[index + 2].Type == TokenType.RoundOpen)
            {
                var codeBlockIndex = ParseUtils.FindTokenIndex(tokens, index, TokenType.CurlyOpen);
                if (codeBlockIndex.HasValue)
                {
                    var function = new FunctionDefinition
                                       {
                                           ReturnType = tokens[index],
                                           Identifier = tokens[index + 1],
                                           ArgumentList = ParseSubExpression(tokens, index + 2, 1, ArgumentListParsers),
                                           CodeBlock =
                                               ParseSubExpression(tokens, codeBlockIndex.Value, 1, CodeBlockParsers)
                                       };
                    function.StringIndex = function.ReturnType.Index;
                    function.Add(new SingleToken() { Token = function.ReturnType});
                    function.Add(new SingleToken() { Token = function.Identifier });
                    if (function.ArgumentList != null) function.Add(function.ArgumentList);
                    if (function.CodeBlock != null) function.Add(function.CodeBlock);
                    function.TokenLength = codeBlockIndex.Value - index + function.CodeBlock.TokenLength;

                    var lastToken = tokens[index + function.TokenLength - 1];
                    function.StringLength = lastToken.Index + lastToken.Value.Length - function.StringIndex;

                    return function;

                }
            }
            return null;
        }

        public List<ExpressionParser> ArgumentListParsers { get; set; }
        public List<ExpressionParser> CodeBlockParsers { get; set; }

    }
}
